import axios from "axios";
import qs from "qs";
/**
 * 统一的错误提示
 * */
const errorTip = (message, code = null) => {
  const msg = message.length > 30 ? "运行报错" : message;
  console.error("错误====>===>", message, code);
};

/**
 * axios全局设置
 */
const $axios = axios.create({
  headers: {
    "Content-Type": "application/x-www-form-urlencoded;charset=UTF-8",
    Accept: "application/json",
    "X-Requested-With": "XMLHttpRequest",
  },
  timeout: 1000 * 10,
  withCredentials: true,
  paramsSerializer: function (params) {
    // 请求数组需要
    return qs.stringify(params, { arrayFormat: "brackets" });
  },
});

$axios.interceptors.request.use(
  axiosConfig => {
    return axiosConfig;
  },
  error => {
    errorTip(error.response);
  }
);
$axios.interceptors.response.use(
  response => {
    return response;
  },
  error => {
    errorTip(error.response);
    return Promise.reject(error);
  }
);

export default {
  // get请求
  get(url, param) {
    return new Promise((resolve, reject) => {
      $axios({
        method: "get",
        url,
        params: param,
      })
        .then(res => {
          resolve(res);
        })
        .catch(error => {
          reject(error.response);
        });
    });
  },
  // post请求
  post(url, param) {
    return new Promise((resolve, reject) => {
      $axios({
        method: "post",
        url,
        data: param,
        headers: {
          "Content-Type": "application/json",
        },
      })
        .then(res => {
          resolve(res);
        })
        .catch(error => {
          reject(error.response);
        });
    });
  },
  // 文件上传请求
  filePost(url, param) {
    return new Promise((resolve, reject) => {
      $axios({
        method: "post",
        url,
        data: param,
        headers: {
          "Content-Type": "multipart/form-data",
        },
      })
        .then(res => {
          resolve(res);
        })
        .catch(error => {
          reject(error.response);
        });
    });
  },
};
